package com.lancoo.cvas.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lancoo.cvas.entity.*;
import com.lancoo.cvas.mapper.ScheduleMapper;
import com.lancoo.cvas.pojo.common.Deleted;
import com.lancoo.cvas.pojo.constant.GlobalConstant;
import com.lancoo.cvas.pojo.dto.TeachingClassTimeCode;
import com.lancoo.cvas.pojo.excel.*;
import com.lancoo.cvas.pojo.response.Scheme;
import com.lancoo.cvas.pojo.vo.StudentTeachingClass;
import com.lancoo.cvas.service.*;
import com.lancoo.cvas.util.MyExcelUtils;
import com.lancoo.cvas.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "任务控制器")
@RestController
@Slf4j
@RequestMapping("/api/v5.0.1/web/test")
public class TestController {

    @Resource
    private YunService yunService;

    @Autowired
    private ResourceLoader resourceLoader;
    @Resource
    private PlanTeachingService planTeachingService;

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private TeachingClassService teachingClassService;
    @Resource
    private ScheduleService scheduleService;
    @Resource
    private ScheduleMapper scheduleMapper;
    @Resource
    private TaskInfoService taskInfoService;
    @Resource
    private StudentService studentService;
    @Resource
    private TeachingClassStudentService teachingClassStudentService;



    @ApiOperation("获取基础平台学校学期")
    @GetMapping("/test")
    public String getTermInfo() {
//        String classInfoPath = teachingClassService.allTeachingClassToExcel(138);
//        String scheduleInfoPath = scheduleService.allScheduleToExcel(138);
//        return GlobalConstant.MODEL_EXCEL_PATH + "UploadTimeProhibit.xlsx";


        List<TaskInfo> taskInfoList = taskInfoService.lambdaQuery().eq(TaskInfo::getDeleted, Deleted.NOT.getCode()).list();
        if (CollUtil.isNotEmpty(taskInfoList)) {
            taskInfoList.forEach(o -> {
                yunService.syncTeacher(o.getTaskId(), o.getSchoolId(), o.getTerm());
            });

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YY:MM:DD HH:MM:SS");
            String currTime = LocalDateTime.now().format(formatter);

            log.info("现在的时间" + currTime);
        } else {
            log.error("没有开课计划，不需要初始化教师信息");
        }

        return null;


    }



    @ApiOperation("获取基础平台学校学期")
    @GetMapping("/test1")
    public String aa(@RequestParam Integer taskId) {
//        teachingClassService.allTeachingClassToExcel(taskId);
//        scheduleService.allScheduleToExcel(taskId);
//        return "";

//        TeachingClass one = teachingClassService.lambdaQuery().eq(TeachingClass::getTaskId, 7).one();

//        int i = 1+1;
        return "";
    }

    @ApiOperation("获取基础平台学校学期")
    @GetMapping("/test2")
    public void aaa(@RequestParam Integer taskId, HttpServletResponse response) {
        List<Student> list = studentService.lambdaQuery().eq(Student::getTaskId, taskId)
                .in(Student::getGradeName, new ArrayList<String>(Arrays.asList("2021级", "2022级"))).list();
        if (CollUtil.isNotEmpty(list)) {

            List<String> collect = list.stream().map(Student::getBaseStudentId).distinct().collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect)) {
                List<StudentDto> studentDtos = new ArrayList<>();
                collect.forEach(o -> {
                    studentDtos.add(new StudentDto().setBaseStudentId(o));
                });

                String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

                MyExcelUtils.exportExcel(studentDtos,
                        "学生学号",
                        "学生学号",
                        StudentDto.class,
                        "学生学号" + time + ".xls", response);

            }
        }
    }


    @ApiOperation("获取基础平台学校学期")
    @GetMapping("/test3")
    public void aaaa(@RequestParam Integer taskId, HttpServletResponse response) {
        List<ViewSchedule> allSchedule = scheduleMapper.getAllSchedule(new ArrayList<>(Arrays.asList(2)));
        Map<Long, List<ViewSchedule>> collect = allSchedule.stream().collect(Collectors.groupingBy(ViewSchedule::getTeachingClassId));
        collect.forEach((key, value) -> {
            List<TeachingClassTimeCode>  teachingClassTimeCodes = new ArrayList<>();
            for (ViewSchedule viewSchedule : value) {
                TeachingClassTimeCode teachingClassTimeCode = new TeachingClassTimeCode();
                teachingClassTimeCode.setCourseId(viewSchedule.getCourseId());
                teachingClassTimeCode.setTimeCode(viewSchedule.getTimeCode());
                teachingClassTimeCodes.add(teachingClassTimeCode);
            }
            Map<String,List<TeachingClassTimeCode>> map = new HashMap<>();
            map.put(String.valueOf(key),teachingClassTimeCodes);
            redisUtil.hmset4(getCacheKeys(2, null, 7, null), map,60*60*24);
        });

        HashMap<String,List<TeachingClassTimeCode>> teachingClassCode = new HashMap<>();
        redisUtil.hmget(getCacheKeys(2, null, 7, null)).forEach((key,value)->{
            teachingClassCode.put(String.valueOf(key),(List<TeachingClassTimeCode>) value);
        });
    }


    public String getCacheKeys(Integer taskId, Long uniqueIdentify, int type, String standby) {
         /*
        返回值用StringBuilder 速度快
        1:存储教学班都有哪些学生  key->teachingClassId
        2:存储学生都选了哪些教学班，教学班详情  key->studentId
        3:存储教学班对应学生数据，然后同步到数据库
        4:学生可选教学班 key->studentId value -> Set<TeachingClassId>
        5:学生已选教学班
        6：教学班详情 包括课表 余量等
         */
        StringBuilder key = new StringBuilder();
        key.append(GlobalConstant.REDIS_PREFIX).append(taskId).append(StrUtil.C_COLON);
        switch (type) {
            case 1:
                return key.append("TeachingStudentId").append(StrUtil.C_COLON).append(uniqueIdentify).toString();
            case 2:
                return key.append("StudentTeachingClass").append(StrUtil.C_COLON).append(uniqueIdentify).toString();
            case 3:
                return key.append("TeachingClassStudent").toString();
            case 4:
                return key.append("StudentOptionalClass").append(StrUtil.C_COLON).append(uniqueIdentify).append(StrUtil.C_COLON).append(standby).toString();
            case 5:
                return key.append("StudentSelectedClass").append(StrUtil.C_COLON).append(uniqueIdentify).toString();
            case 6:
                return key.append("TeachingClassDetail").toString();
            case 7:
                return key.append("TeachingClassCode").toString();
            default:
                return "";
        }
    }





}
